package com.sample.ch4session.sec1hiddenField;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/questionnaire_hidden")
public class Questionnaire extends HttpServlet {
    protected void processRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        //单引号会原样输出
        out.println("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01"+"Transitional//EN'>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>在线问答</title>");
        out.println("</head>");
        out.println("<body>");
        // 请求参数决定显示哪一页问卷
        String page = req.getParameter("page");
        out.println("<form action='questionnaire' method='post'>");
        if (page==null) {
            out.println("问题1: <input type='text' name='p1q1'> <br>");
            out.println("问题2: <input type='text' name='p1q2'> <br>");
            out.println("<input type='submit' name='page' value='下一页'>");
        } else if ("下一页".equals(page)){
            // 把第一步的答案暂存并返回给浏览器以hidden方式，
            String p1q1 = req.getParameter("p1q1");
            String p1q2 = req.getParameter("p1q2");
            out.println("问题三 : <input type='text' name='p2q1'><br>");
            out.println("<input type='hidden' name='p1q1' value='"+p1q1+"'>");
            out.println("<input type='hidden' name='p1q2' value='"+p1q2+"'>");
            out.println("<input type='submit' name='page' value='完成'>");
        } else if ("完成".equals(page)){
            // 问卷结果
            out.println(req.getParameter("p1q1")+"<br>");
            out.println(req.getParameter("p1q2")+"<br>");
            out.println(req.getParameter("p2q1")+"<br>");
        }
        out.println("</form>");
        out.println("</body>");
        out.println("</html>");
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp);
    }
}
